package main

import (
	"context"
	"fmt"
	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"learningProject/mytest/consulTest/pb"
	"net"
)

// 定义类
type Children struct {
}

// 按接口绑定类方法,是pb文件里的interface
func (c *Children) SayHello(ctx context.Context, t *pb.Person) (*pb.Person, error) {
	t.Name += " say hello"
	return t, nil
}
func main() {
	//////// 将grpc绑定到consul  /////////////
	// 初始化consul配置
	consulConfig := api.DefaultConfig()

	// 创建consul对象
	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		fmt.Println("api.NewClient err", err)
		return
	}

	// 告诉consul即将注册的服务的配置信息
	registerService := api.AgentServiceRegistration{
		ID:      "bj38",                     // id
		Tags:    []string{"grpc", "consul"}, // 服务别名
		Name:    "grpc and consul",          // 服务名
		Port:    8800,                       // grpc服务的端口，consul的端口是8500
		Address: "127.0.0.1",
		Check: &api.AgentServiceCheck{
			CheckID:  "check666",
			TCP:      "127.0.0.1:8800",
			Timeout:  "1s",
			Interval: "5s",
		},
	}

	// 注册grpc服务到consul
	consulClient.Agent().ServiceRegister(&registerService)

	//////////  grpc   ////////
	// 初始化一个grpc对象
	grpcServer := grpc.NewServer()

	// 注册服务
	pb.RegisterHelloServer(grpcServer, &Children{})

	// 设置监听，指定ip和端口
	listener, err := net.Listen("tcp", "127.0.0.1:8800")
	if err != nil {
		fmt.Println("listen err:", err)
	}
	defer listener.Close()
	fmt.Println("服务启动")

	// 启动服务
	grpcServer.Serve(listener)
}
